package xiaodou.modules.overview
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.utils.Dictionary;
	
	import xiaodou.modules.overview.data.ContrastData;
	import xiaodou.modules.overview.data.OneDayData;
	
	public class GatherModel extends EventDispatcher
	{
		/**
		 * 统计信息，每一项是GatherDatao类型的array，以AccountName为键
		 */		
		private var _gatherDic:Dictionary;
		
		public function GatherModel(target:IEventDispatcher=null)
		{
			super(target);
			_gatherDic = new Dictionary();
		}
		
		/**
		 * 添加统计数据 
		 * @param arr 统计数据集合，每一项是GatherData
		 * 
		 * @see xiaodou.modules.overview.GatherData
		 * 
		 */		
		public function addGatherData(arr:Array):void
		{
			for each(var item:OneDayData in arr)
			{
				if(_gatherDic[item.AccountName] == null)
					_gatherDic[item.AccountName] = new Array();
				_gatherDic[item.AccountName].push(item);
			}
			dispatchEvent(new GatherEvent(GatherEvent.GATHER_DATA_ADDED));
		}
		
		/**
		 * 获取某个帐号的的对比数据
		 * @param firstDate 第一个数据对应的日期，若不传参数，默认取前天
		 * @param secondeDate 第二个数据对应的日期，若不取参数，默认取昨天
		 * @return 
		 * 
		 */		
		public function getContrastData(account:String, firstDate:Date = null, secondDate:Date = null):ContrastData
		{
			if(secondDate == null)					//默认取昨天
			{
				secondDate = new Date();
				secondDate.date -= 1;
			}
			if(firstDate == null)					//默认取前昊
			{
				firstDate = new Date();
				firstDate.date -= 2;
			}
			var firstData:OneDayData = getOneDayData(account, firstDate);
			var secondData:OneDayData = getOneDayData(account, secondDate);
			if(firstData && secondData)
				return new ContrastData(firstData, secondData);
			return null;
		}
		
		private function getOneDayData(account:String, date:Date):OneDayData
		{
			if(_gatherDic[account] == null)
				return null;
			for each(var item:OneDayData in _gatherDic[account])
			{
				if(item.date.fullYear == date.fullYear && item.date.month == date.month && item.date.date == date.date)
					return item;
			}
			return null;
		}
	}
}